﻿#include "button.h"
#include <QPainter>
#include <QPaintEvent>
#include <QPixmap>
#include <QLabel>
#include <QDebug>

Button::Button(QString FileName, int xnum, QWidget* parent,
    int ynum, QString bkGrnd) :QPushButton(parent)
{
    QPixmap pixmap(FileName);

    for (int cnt = 0; cnt < xnum; ++cnt)
    {
        for (int y = 0; y < ynum; ++y)
        {
            pixmatpVector->push_back(pixmap.copy(cnt * (pixmap.width() / xnum),
                y * (pixmap.height() / ynum),
                pixmap.width() / xnum,
                pixmap.height() / ynum));
        }
    }

    if (bkGrnd.isEmpty())
        background = new QPixmap(bkGrnd);
    else
        background = NULL;

    setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
    curIndex = 0;
}

Button::Button(QVector<QString>& list, QWidget* parent,
    QString bkGrnd) :QPushButton(parent)
{
    setPixmapList(list);
    setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);

    if (bkGrnd.isEmpty())
        background = new QPixmap(bkGrnd);
    else
        background = NULL;

    curIndex = 0;
}
Button::Button(QVector<QPixmap>* FileName, QWidget* parent)
    :QPushButton(parent)
{
    pixmatpVector = FileName;
}

void Button::setPixmaps(QVector<QPixmap>* vector)
{
    pixmatpVector = vector;
}

void Button::setPixmapList(QVector<QString>& list)
{
    if (list.size() <= 0) return;
    pixmatpVector->clear();

    for (QVector<QString>::iterator pos = list.begin();
        pos != list.end(); ++pos)
    {
        pixmatpVector->push_back(QPixmap(*pos));
    }
}

void Button::paintEvent(QPaintEvent* event)
{
    QPainter painter(this);
    painter.drawPixmap(event->rect(), pixmatpVector->at(curIndex));
   
}

void Button::enterEvent(QEnterEvent* event)
{
    if (pixmatpVector->size() > 1)
        curIndex = 1;
    else
        curIndex = 0;
    update();
    QPushButton::enterEvent(event);
}

void Button::leaveEvent(QEvent* event)
{
    curIndex = 0;
    update();
    QPushButton::leaveEvent(event);
}

void Button::mousePressEvent(QMouseEvent* event)
{
    if (event->button() == Qt::LeftButton)
    {
        if (pixmatpVector->size() > 2)
        {
            curIndex = 2;
            update();
        }
    }
    QPushButton::mousePressEvent(event);
}

void Button::mouseReleaseEvent(QMouseEvent* event)
{
    if (event->button() == Qt::LeftButton)
    {
        if (pixmatpVector->size() > 1)
        {
            curIndex = 1;
            update();
        }
    }
    QPushButton::mouseReleaseEvent(event);
}

QSize Button::sizeHint() const
{
    return background != NULL ? QSize(background->width(), background->height()) :
        QSize(pixmatpVector->at(0).width(), pixmatpVector->at(0).height());
}